//package com.navi.loaddata.loadService.impl.measureData;
//
//import com.navi.loaddata.core.errorLog.ErrorLog;
//import com.navi.loaddata.core.etlException.ETLException;
//import com.navi.loaddata.core.gpEntity.GpChipF;
//import com.navi.loaddata.core.gpEntity.GpDefectF;
//import com.navi.loaddata.core.gpEntity.GpGlassF;
//import com.navi.loaddata.core.gpEntity.MppLayoutPnlD;
//import com.navi.loaddata.core.mesEntity.MesProducthistory;
//import com.navi.loaddata.core.mysqlEntity.EtlConfDModel;
//import com.navi.loaddata.core.oracleEntity.*;
//import com.navi.loaddata.core.repository.impl.OracleRepositoryImpl;
//import com.navi.loaddata.core.util.LoggerUtil;
//import com.navi.loaddata.loadDao.SaveBaseDataDao;
//import com.navi.loaddata.loadDao.SaveFileDataDao;
//import com.navi.loaddata.loadService.impl.baseData.LoadMesBaseDataService;
//import com.navi.loaddata.loadService.impl.baseData.ProcessBaseDataService;
//import org.apache.commons.collections.map.HashedMap;
//import org.apache.commons.lang.StringUtils;
//import org.hibernate.Session;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//import static java.util.stream.Collectors.groupingBy;
//
///**
// * @author xufan
// */
//@Service
//@Transactional(transactionManager = "thirdaryPlatformTransactionManager",
//        rollbackFor = {RuntimeException.class, Exception.class})
//public class LoadMeasureDataService {
//    private static final Logger logger = LoggerFactory.getLogger(LoadMeasureDataService.class);
//    private LoggerUtil loggerUtil = new LoggerUtil(this.getClass());
//
//    @Autowired
//    private OracleRepositoryImpl dao3;
//    @Autowired
//    private LoadMesBaseDataService loadMesBaseDataService;
//
//    @Autowired
//    private ProcessBaseDataService processBaseDataService;
//    @Autowired
//    private ProcessDefectDataService processDefectDataService;
//    @Autowired
//    private LoadDefectInfoService loadDefectInfoService;
//    @Autowired
//    private SaveBaseDataDao saveBaseDataDao;
//    @Autowired
//    private SaveFileDataDao saveFileDataDao;
//
//
//    public String[] loadMeasureDataMain(EtlConfDModel etlConfD) throws ETLException {
//        String[] resMsg=new String[3];
//
//        Session session = dao3.getEntityManagerSession();
//        try {
//            resMsg = loadMeasureData(session, etlConfD);
//            String msg=etlConfD.getOpe();
//
//            if(StringUtils.isEmpty(etlConfD.getOpe())) msg="ALL";
//            logger.info("OpeId={} LoadMeasureDataMain finish!",msg);
//        } catch (ETLException e) {
//            throw new ETLException(e.getMessage());
//        }
//        return resMsg;
//    }
//
//    /**
//     * Load Measure Data
//     * <p>
//     * load base -> session table
//     * load defect data  -> session table
//     * call base proc  -> auto commit
//     * call defect proc -> no auto commit
//     * delete defect session table
//     *
//     * @param session
//     * @param etlConfD
//     */
//    private String[] loadMeasureData(Session session, EtlConfDModel etlConfD) throws ETLException {
//        String[] resMsg=new String[3];
//        int okCnt = 0;
//        int errCnt=0;
//        String errMsg=null;
//
//        // defect glass
//        List<GpGlassF> defectGlassList = loadDefectInfoService.loadGlassInfo(etlConfD);
//        logger.info("{} defect glass count {}", etlConfD.getShop(), defectGlassList.size());
//
//        if (!defectGlassList.isEmpty()) {
//            //getMap坐标
//            HashMap<String,List<MppLayoutPnlD>> layoutPnlMap=new HashMap<>();
//            try {
//                if ("CELL2".equals(etlConfD.getCellType())) {
//                    layoutPnlMap = loadDefectInfoService.small2big(defectGlassList);
//                } else {
//                    layoutPnlMap = loadDefectInfoService.big2small(defectGlassList);
//                }
//            } catch (Exception e) {
//                logger.error(LoggerUtil.stackTraceToString(e));
//                throw new ETLException("getMap坐标失败。");
//            }
//
//            // base
//            List<EtlStepV> etlStepVList = new ArrayList<>();
//            List<EtlProductV> etlProductVList = new ArrayList<>();
//            try {
//                etlStepVList = loadMesBaseDataService.loadAllFinalStep(etlConfD.getShop(), ErrorLog.ERROR_PROCESS_STEP_V, logger);
//                etlProductVList = loadMesBaseDataService.loadAllFinalProduct(etlConfD.getShop(), ErrorLog.ERROR_PROCESS_PRODUCT_V, logger);
//            } catch (Exception e) {
//                logger.error("[{}] - [{}] GET BASE_DATA ERROR", etlConfD.getRunStartTimestamp(), etlConfD.getRunEndTimestamp());
//                throw new ETLException(e.getMessage());
//            }
//
//            // save base and proc
//            try {
//                saveBaseDataDao.saveBaseData(session, etlConfD, etlStepVList, etlProductVList);
//            } catch (Exception e) {
//                throw e;
//            }
//
//            Map<String, String> mOpeDList = loadDefectInfoService.loadMOpeDInfo(etlConfD);
//            Map<String, List<GpGlassF>> glassDataTree =
//                    defectGlassList.stream().collect(groupingBy(GpGlassF::getGlassId));
////            long time = Long.valueOf(0);
//
//            for (Map.Entry<String, List<GpGlassF>> entry : glassDataTree.entrySet()) {
////                long enterTime = System.currentTimeMillis();
//                List<GpGlassF> curGlassList = entry.getValue();
//                //common
//                //OC不需要BASE DATA
//                if (!"OC".equals(etlConfD.getShop())) {
//                    List<MesProducthistory> cmnGlassVList =
//                            loadMesBaseDataService.loadCommonGlassInfo(etlConfD, curGlassList.get(0).getGlassId());
//                    if (cmnGlassVList.size() == 0) {
//                        continue;
//                    }
//                    List<EtlCmnGlassV> etlCmnGlassVList = new ArrayList<>();
//                    try {
//                        etlCmnGlassVList = processBaseDataService.processCmnGlass(cmnGlassVList, ErrorLog.ERROR_PROCESS_CMN_GLASS_V, logger);
//                    } catch (Exception e) {
//                        logger.error("[{}] - [{}] PROCESS CMN_GLASS_DATA  ERROR", etlConfD.getRunStartTimestamp(), etlConfD.getRunEndTimestamp());
//                        throw new ETLException(curGlassList.get(0).getGlassId() + ":" + e.getMessage());
//                    }
//                    // save and proc
//                    try {
//                        saveBaseDataDao.saveCmnGlass(session, etlConfD, etlCmnGlassVList, curGlassList.get(0).getGlassId());
//                    } catch (Exception e) {
//                        throw e;
//                    }
//                }
//
//                //panel
//                Map<String, List<GpChipF>> defectPanelMap = new HashedMap();
//                if (!"CELL2".equals(etlConfD.getCellType())) {//CELL2 没有chip
//                    defectPanelMap = loadDefectInfoService.loadPanelInfo(etlConfD, curGlassList);
////                        logger.info("{} defect panel count {}", etlConfD.getShop(),defectPanelMap.size());
//                }
//
//                //defect
//                Map<String, List<GpDefectF>> defectMap =
//                        loadDefectInfoService.loadDefectInfo(etlConfD, curGlassList);
//
//                Map<String, List<EtlGlassV>> etlGlassVMap = new HashedMap();
//                Map<String, List<EtlChipV>> etlChipVMap = new HashedMap();
//                Map<String, List<EtlDefectV>> etlDefectVMap = new HashMap<>();
//
//
////                enterTime = System.currentTimeMillis();
//                for (GpGlassF glass : curGlassList) {
//                    try {
//                        etlGlassVMap.put(glass.getUnqSeqId(), processDefectDataService.processGlass(etlConfD, glass, ErrorLog.ERROR_PROCESS_GLASS_V, logger));
//                        if (!"CELL2".equals(etlConfD.getCellType())) {
//                            etlChipVMap.put(glass.getUnqSeqId(), processDefectDataService.processPanel(etlConfD, defectPanelMap.get(glass.getUnqSeqId()), ErrorLog.ERROR_PROCESS_CHIP_V, logger));
//                        }
//                        etlDefectVMap.put(glass.getUnqSeqId(), processDefectDataService.processDefect(layoutPnlMap.get(glass.getGlassId().substring(0,10)), etlConfD, defectMap.get(glass.getUnqSeqId()), mOpeDList, ErrorLog.ERROR_PROCESS_DEFECT_V, logger));
//
//
//                    } catch (Exception e) {
//                        logger.error("[{}] - [{}] PROCESS FILE_DATA  ERROR", etlConfD.getRunStartTimestamp(), etlConfD.getRunEndTimestamp());
//                        throw new ETLException("PROCESS错误：" + glass + ":" + e.getMessage());
//                    }
//                }
//
//
//                for (String key : etlGlassVMap.keySet()) {
////                    if(!("A185G00RBB".equals(etlGlassVMap.get(key).get(0).getGlassId())&&"A1853".equals( etlGlassVMap.get(key).get(0).getStepId()))) continue;
//                    try {
//                        //save and proc
//                        saveFileDataDao.saveFileData(session, etlConfD, etlGlassVMap.get(key), etlChipVMap.get(key), etlDefectVMap.get(key), etlGlassVMap.get(key).get(0).getGlassId());
//
////                        try{
////                            Thread thread = Thread.currentThread();
////                            thread.sleep(1000);//暂停0.5秒后程序继续执行,给存储过程执行时间
////                        }catch (InterruptedException ex) {
////                            logger.error(LoggerUtil.stackTraceToString(ex));
////                        }
//                        //清空Session表CELL2_CHIP_V
//                        saveFileDataDao.deleteFile(session, etlConfD);
//                        logger.info("glassId={},opeId={},procEndTime={} 保存成功!", etlGlassVMap.get(key).get(0).getGlassId(), etlGlassVMap.get(key).get(0).getStepId(), etlGlassVMap.get(key).get(0).getGlassEndTime().toString());
//
//                        okCnt++;
//                    }catch (Exception e){
//                        logger.error("glassId=" + etlGlassVMap.get(key).get(0).getGlassId()
//                                + ",opeId=" + etlGlassVMap.get(key).get(0).getStepId()
//                                + ",procEndTime=" + etlGlassVMap.get(key).get(0).getGlassEndTime().toString()
//                                + "保存失败,错误原因：");
//                        logger.error(LoggerUtil.stackTraceToString(e));
//                        errCnt++;
//                        if(!StringUtils.isEmpty(errMsg)) {
//                            errMsg = errMsg
//                                    + "glassId=" + etlGlassVMap.get(key).get(0).getGlassId()
//                                    + ",opeId=" + etlGlassVMap.get(key).get(0).getStepId()
//                                    + ",procEndTime=" + etlGlassVMap.get(key).get(0).getGlassEndTime().toString()
//                                    + "保存失败,错误原因：" + e.getMessage() + "。\n";
//                        }else{
//                            errMsg="glassId=" + etlGlassVMap.get(key).get(0).getGlassId()
//                                    + ",opeId=" + etlGlassVMap.get(key).get(0).getStepId()
//                                    + ",procEndTime=" + etlGlassVMap.get(key).get(0).getGlassEndTime().toString()
//                                    + "保存失败,错误原因：" + e.getMessage() + "。\n";
//                        }
//                    }
//
//                }
////                    saveBaseDataDao.deleteCmnGlass(session, etlConfD);
//            }
//        } else {
//            logger.info("没有此区间的数据。"); // todo print log & save etl data
//        }
//        resMsg[0]=String.valueOf(okCnt);
//        resMsg[1]=String.valueOf(errCnt);
//        resMsg[2]=errMsg;
//
//        return resMsg;
//    }
//
//    public <T> void saveAll(List<T> entities, int errorViewLog, String glassId) throws ETLException {
//        try {
//            dao3.saveAll(entities);
//        } catch (Exception e) {
//            logger.error(errorViewLog + ":" + e.getMessage());
//            logger.error(LoggerUtil.stackTraceToString(e));
//            throw new ETLException(glassId + ":" + errorViewLog + ":" + e.getMessage());
//        }
//    }
//
//}
